package com.wiz.weixin.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    /**
     * 对字符串进行MD5编码
     *
     * @param originstr 需要加密字符串
     * @return 加密结果
     */
    public static String encode(String originstr) {
        if (originstr != null) {
            try {
                //创建具有指定算法名称的信息摘要
                MessageDigest md = MessageDigest.getInstance("MD5");
                //使用指定的字节数组对摘要进行最后的更新，然后完成摘要计算
                byte[] results = md.digest(originstr.getBytes());
                //将得到的字节数组编程字符窜返回
                return byte2Hex(results);
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }
        return null;
    }
    
    /**
     * Encodes a string
     * 
     * @param str String to encode
     * @return Encoded String
     * @throws Exception
     */
    public static String crypt(String str)
    {
        if (str == null || str.length() == 0) {
            throw new IllegalArgumentException("String to encript cannot be null or zero length");
        }
        
        StringBuffer hexString = new StringBuffer();
        
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] hash = md.digest();
            
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) {
                    hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
                }               
                else {
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
                }               
            }
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
        return hexString.toString();
    }

    /**
     * 验证密码是否正确
     *
     * @param string       字符串
     * @param encodeString MD5串
     * @return 比较结果
     */
    public static boolean checkEquals(String string, String encodeString) {
        return string.equals((encode(encodeString)));
    }

    /**
     * @param paramArrayOfByte 字符数组
     * @return 十六进制转换结果
     */
    private static String byte2Hex(byte[] paramArrayOfByte) {
        StringBuilder stringBuilder = new StringBuilder();
        String str;
        for (byte aParamArrayOfByte : paramArrayOfByte) {
            str = Integer.toHexString(aParamArrayOfByte & 0xFF);
            if (str.length() == 1)
                stringBuilder.append("0");
            stringBuilder.append(str);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        System.out.println(encode("123456"));
        //out:96e79218965eb72c92a549dd5a330112
    }


}
